﻿using FreeSql;
using FYSJcrm.Core.IRepository.PermManage;
using FYSJcrm.Core.Model.PermManage;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace FYSJcrm.Core.Repository.PermManage
{
    public class ManagerRepository : BaseRepository<ManagerEntity>, IManagerRepository
    {
        private IFreeSql _freeSql;

        public ManagerRepository(IFreeSql fsql) : base(fsql, null, null)
        {
            _freeSql = fsql;
        }

        public async Task<bool> HasPermissionAsync(int adminUserId, string permissionName)
        {
            var managerRepository = _freeSql.GetRepository<ManagerEntity>();
            var roleRepository = _freeSql.GetRepository<ManagerRoleEntity>();

            var manager = await managerRepository.Select.Where(p => p.Id == adminUserId).FirstAsync();
            if (manager == null)
            {
                throw new ArgumentException("找不到Id=" + adminUserId + "的用户");
            }

            var roles = await roleRepository.Select.IncludeMany(p => p.Permissions).Where(p => p.Id == manager.RoleId).FirstAsync(); ;

            return roles.Permissions.Any(p => p.Name == permissionName);
        }
    }
}
